package net.asfun.jvalog.http;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import static net.asfun.jvalog.misc.Log.logger;
import net.asfun.jvalog.except.InteractException;
import net.asfun.jvalog.misc.ThreadHelper;
import net.asfun.jvalog.misc.Setting;

public class ConsoleServlet extends HttpServlet {

	private static final long serialVersionUID = 200905031506L;
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String act = RequestUtil.getStringParam(req, "a", "Index");
		String fun =  RequestUtil.getStringParam(req, "d", "index");
		logger.finer("action="+act+"||method="+fun);
		try {
			ThreadHelper.startup();
			Class clz = Class.forName("net.asfun.jvalog.action." + act + "Action");
			Object obj = clz.newInstance();
			Method mth = clz.getMethod(fun, new Class[]{HttpServletRequest.class, HttpServletResponse.class});
			mth.invoke(obj, new Object[]{req, resp});
		} catch (InvocationTargetException ie) {
			if ( ie.getTargetException().getClass() == InteractException.class) {
				//TODO treat ajax & normal diffentily
				String message = null;
				try {
					JSONObject json = new JSONObject();
					json.put("type", "error");
					json.put("message", ie.getTargetException().getMessage());
					message = json.toString();
				} catch (JSONException e) {
					message = "{type:\"error\",message:\"json error\"}";
					logger.log(Level.SEVERE, e.getMessage(), e);
				}
				resp.setContentType("text/plain");
				resp.getWriter().println(message);
			} else {
				logger.log(Level.SEVERE, ie.getMessage(), ie);
				resp.getWriter().print(Setting.errorPage);
			}
		} catch ( Exception e) {
			logger.log(Level.INFO, e.getMessage(), e);
			resp.sendRedirect("/jva.log");
		}
		ThreadHelper.shutdown();
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		doGet(req, resp);
	}
	
	public void init(ServletConfig config) {
		Setting.root = config.getServletContext().getRealPath("/");
	}
	
}
